package com.ruoyi.extdata.common;

import com.ruoyi.bizsys.domain.AppUser;
import com.ruoyi.bizsys.service.IAppUserService;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.Func;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author cyh
 */
@Slf4j
@Component
public class SecureUtil {

    @Value("${token.header}")
    private String header;

    @Value("${token.secret}")
    private String secret;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    IAppUserService appUserService;

    public String getUserId() {
        String userId = null;
        LoginUser loginUser = parseUser(ServletUtils.getRequest());
        if (loginUser != null) {
            userId = loginUser.getUsername();
        }
        if (Func.isEmpty(userId)) {
            log.warn("用户不存在或登录态失效");
            throw new BusinessException(RspEnmu.ILLEGAL_USER_REQ_ERR);
        }
        return userId;
    }

    public String getAppVersion() {
        String appVersion = ServletUtils.getRequest().getHeader("appVersion");
        if (Func.isEmpty(appVersion)) {
            throw new BusinessException(RspEnmu.APP_VERSION_DONOT_SUPPORT);
        }
        return appVersion;
    }

    public AppUser getAppUser() {
        AppUser appUser = new AppUser();
        appUser.setUserUuid(this.getUserId());
        List<AppUser> appUsers = appUserService.selectAppUserList(appUser);
        if (CollectionUtils.isEmpty(appUsers)) {
            throw new BusinessException(RspEnmu.USER_NOT_EXIST);
        }
        return appUsers.get(0);
    }


    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser parseUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
            String userKey = getTokenKey(uuid);
            LoginUser user = redisCache.getCacheObject(userKey);
            return user;
        }
        return null;
    }

    private String getTokenKey(String uuid) {
        return Constants.LOGIN_TOKEN_KEY + uuid;
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

}
